package com.shlh.saas.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * XML工具类，用于微信支付XML数据处理
 */
public class XMLUtil {

    /**
     * 将XML字符串转换为Map
     *
     * @param xmlString XML字符串
     * @return 结果Map
     */
    public static Map<String, String> xmlToMap(String xmlString) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            Document document = DocumentHelper.parseText(xmlString);
            Element rootElement = document.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                resultMap.put(element.getName(), element.getTextTrim());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 将Map转换为XML字符串
     *
     * @param map 数据Map
     * @return XML字符串
     */
    public static String mapToXml(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append("<").append(entry.getKey()).append(">");
            sb.append("<![CDATA[").append(entry.getValue()).append("]]>");
            sb.append("</").append(entry.getKey()).append(">");
        }
        sb.append("</xml>");
        return sb.toString();
    }
} 